<?
/*
 * The following system requires the PEAR packages
 * AUTH
 * MDB2
 * MDB2 Mysql Drive
 * Number_Words
 * 
 */

//set_error_handler('error_handler');
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
//error_reporting(E_ALL);

// print 'curent: ' . getcwd();
if (str_contains($_SERVER['PHP_SELF'], "/reports/"))
	include_once("../inc/config.php");
elseif (str_contains($_SERVER['PHP_SELF'], "ajax.php"))
	include_once("../inc/config.php");	
elseif (str_contains($_SERVER['PHP_SELF'], "/pages/"))
	include_once("../inc/config.php");		
else
	include_once("./inc/config.php");
include "Auth.php";
include "MDB2.php";
require_once "Numbers/Words.php";
	
function loginFunction()
{
     /*
      * Change the HTML output so that it fits to your
      * application.
      */
?>
<fieldset>
	<legend>Login</legend>
		<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<form method="post" name="loginform">
				<tr>
					<td valign="top" class="label" width="100" align="right">
			    	User Name :
					</td>
					<td align="right">
			    	<input type="text" name="username" size="20" class="textinput"><br />
			    	Case Sensitive
					</td>
					<td valign="top" class="label" width="100" align="right">
						Password :
					</td>
					<td align="right">
			    	<input type="password" name="password" size="20" class="textinput"><br />
			    	Case Sensitive
					</td>
					<td valign="top" align="center" class="label" width="100">
			    	<input type="submit" value="Login" class="button">
					</td>
				</tr>
		</form>
	</table>
</fieldset>
<?
}

$a = new Auth("MDB2", $params, "loginFunction", TRUE);

//returns current user access level
//requires authenticated user
// @return user_type
function getUserType($string = TRUE) {
	global $a;
	if (isset($a)) {
		$username = $a->getUsername();
		$sql = "select t.user_type, t.user_type_id from er_user e inner join er_user_type t on e.user_type_id = t.user_type_id where username = '$username'";
		$result = r_db($sql);
		//echo "result is ".$result;
		while ($row = mysql_fetch_array($result)) {
			if ($string == TRUE) {
				return $row[0];
			}
			else {
				return $row[1];
			}
		}
	}
}

function r_db($sql) {
	global $dbhost, $dbusername, $dbpassword, $database_name;
	//echo "<pre>$sql</pre>";

	/* Database Stuff, do not modify below this line */
	$con = mysql_connect($dbhost, $dbusername, $dbpassword) or
	   die("Could not connect: " . mysql_error());
	mysql_select_db($database_name, $con);

	$result = mysql_query(strtolower($sql), $con) or die ('Error: '.mysql_error().'<br />'.$sql);

	return $result;
}


function closeDB()
{
	global $dbhost, $dbusername, $dbpassword, $database_name;
    /* Closing connection */
    return mysql_close(connectDB("$dbhost", "$dbusername", "$dbpassword"));
}


function redirectToDefaultPage($userType)
{
	if ($userType == 1 || $userType == 5) // Volunteer or volunteer staff
		header ("Location: WelcomeVolunteer.php");
	elseif ($userType == 2) //ITAdmin
		header ("Location: WelcomeITAdmin.php");
	elseif ($userType == 3)  //ERAdmin
		header ("Location: WelcomeERAdmin.php");
	elseif ($userType == 4)//CEO
		header ("Location: WelcomeCEO.php");

	elseif ($userType == 5)//Staff
		header ("Location: WelcomeStaff.php");
}

function redirectToIndexPage()
{
	header ("Location: http://localhost/Camcare/index.php");
	//echo "Sorry invalid username-password. Try again !";
}

function createSessionUserName($username)
{
	// Register some session variables!
	session_register('session_username');
	$_SESSION['session_username'] = $username;
	return $_SESSION['session_username'];
}

function createSessionClientId($clientId)
{
	// Register some session variables!
	session_register('session_clientId');
	$_SESSION['session_clientId'] = $clientId;
	return $_SESSION['session_clientId'];

	echo "CLIENT ID CREATED - $clientId";
}

function createSessionUserType($userType)
{
	// Register some session variables!
	session_register('session_userType');
	$_SESSION['session_userType'] = $userType;
	return $_SESSION['session_userType'];
}

function createTemplates($leftnav,$content,$title)	//ADDED BY SUMNESH ON 24/06/03
{
	$tpl = new Template('.');
	//assume the templates are in the current directory
	$tpl->set_file(array('std'    =>'std.tpl',					//'std'    =>'std.tpl',
	                   'header' =>'header.tpl',					//'header' =>'header.tpl',
	                   'leftnav'=>$leftnav,				//'leftnav'=>'leftnav.tpl',
	                   'content'=>$content));				//'content'=>'p-10-1.tpl'));
	$tpl->set_var('title',$title);									//'title', 'Generic Web Site');
	$tpl->parse('header',  'header');
	$tpl->parse('leftnav', 'leftnav');
	$tpl->parse('content', 'content');
	$tpl->parse('DUMMY',   'std');
	$tpl->p('DUMMY');
}

function getDates()
{
	/*
	So, to get the current date in DD/MM/YYYY format the command is:
    $current_date = date("d/m/Y");
	You can also get the parts of the date and compare against the given
	date.  To separate out the parts of your date do this:

	    list($day, $month, $year) = explode('/', $date);

	To compare the given date against another it's easiest to use
	timestamps.  To create a timestamp from the given date do this:
    list($day, $month, $year) = explode('/', $date);
    $timestamp = mktime(0, 0, 0, $month, $day, $year);
Note the strange order of the arguments to mktime():
*/
}

function getCurrentDay()
{
	$current_date = date("d/m/Y");
	list($day, $month, $year) = explode('/', $current_date);
	return $day;
}

function getCurrentMonth()
{
	$current_date = date("d/m/Y");
	list($day, $month, $year) = explode('/', $current_date);
	return 	$month;
}

function getCurrentYear()
{
	$current_date = date("d/m/Y");
	list($day, $month, $year) = explode('/', $current_date);
	return $year;
}

function selectFromTable($table,$tableId,$idValue) //ADDED BY RIZWAAN ON 3/6/03
{
	$query="SELECT * FROM " . $table . " WHERE " . $tableId ."='".$idValue . "'" ;
	//echo $query;

	$results=r_db($query);

	$row=mysql_fetch_array($results);

	return $row;

}

function deleteFromTable($table,$tableId,$idValue)//ADDED BY RIZWAAN ON 3/6/03
{
	$query="DELETE FROM " . $table . " WHERE " . $tableId ."='".$idValue . "'" ;
	//echo $query;

	r_db($query);

	$rowsAffected = mysql_affected_rows();

	//$row=mysql_fetch_array($results);

	return $rowsAffected;
}

function getFieldsFromLookUpTable($table,$tableId,$idValue)
{
	$query="SELECT * FROM " . $table . " WHERE " . $tableId ."='".$idValue . "'" ;
	//echo $query;

	$results=r_db($query);

	$row=mysql_fetch_array($results);

	return $row;

}

function getArrayFromTable($table,$tableId,$idValue)//V R USING IT CURRENTLY. DON'T DELETE!!
{
	$arr = array();

	$query="SELECT * FROM " . $table . " WHERE " . $tableId ."='".$idValue . "'" ;
	//echo $query;

	$results=r_db($query);

	while($row= mysql_fetch_object($results))
	{
    	array_push($arr, $row);
  	}

  return $arr;

}

function getAllRecordsFromLookUpTable($table)
{
	$query="SELECT * FROM " . $table;
	//echo $query;

	$results=r_db($query);

	return $results;

}

function get_labels($table_name) {
  /* make an array */
  $arr = array();

  /* construct the query */
  $query = "SELECT * FROM $table_name";

  /* execute the query */
  $qid = r_db($query);
  /* each row in the result set will be packaged as
     an object and put in an array */
  while($row= mysql_fetch_object($qid)) {
    array_push($arr, $row);
  }

  return $arr;
}

function get_labels_er($table_name) {
  /* make an array */
  $arr = array();

  /* construct the query */
  $query = "SELECT * FROM $table_name ORDER BY er_id";

  /* execute the query */
  $qid = r_db($query);
  /* each row in the result set will be packaged as
     an object and put in an array */
  while($row= mysql_fetch_object($qid)) {
    array_push($arr, $row);
  }

  return $arr;
}

function get_labels_actionTaken($table_name) {
  /* make an array */
  $arr = array();

  /* construct the query */
  $query = "SELECT * FROM $table_name ORDER BY action_id";

  /* execute the query */
  $qid = r_db($query);
  /* each row in the result set will be packaged as
     an object and put in an array */
  while($row= mysql_fetch_object($qid)) {
    array_push($arr, $row);
  }

  return $arr;
}
 function get_labels_addvisit($table_name) {

  $i = 2;

  /* make an array */
  $arr_addvisit = array();

  /* construct the query */
  $query_addvisit = "SELECT * FROM er_payment WHERE payment_id != $i";

  /* execute the query */
  $qid_addvisit = r_db($query_addvisit);

  /* each row in the result set will be packaged as
     an object and put in an array */
  while($row= mysql_fetch_object($qid_addvisit)) {
    array_push($arr_addvisit, $row);
  }

  return $arr_addvisit;
}


function populateDropDownListBoxes($table,$rowPosition, $field)
{
	$query="SELECT * FROM $table ORDER BY $field" ;
	//echo $query;

	$results=r_db($query);

	while ($row=mysql_fetch_array($results))
	{
		if ($row[$rowPosition]!="Other")
		echo "<option>$row[$rowPosition]</option>";
	}
	echo "<option>Other</option>";
}

function populateSelectedDropDownListBoxes($table,$rowPosition, $selected, $field)
{
	$query="SELECT * FROM $table ORDER BY $field";
	//echo $query;

	$results=r_db($query);

	while ($row=mysql_fetch_array($results))
	{
		//echo "$row[$rowPosition]";
		if ($row[$rowPosition]!="Other")
		{
			if($row[$rowPosition]==$selected)

			echo "<option selected>$row[$rowPosition]</option>";

			else

			echo "<option>$row[$rowPosition]</option>";
		}
		else
		{
			if($selected=="Other" || $row[$rowPosition]==$selected)
			echo "<option selected>Other</option>";
			else
			echo "<option>Other</option>";
		}
	}
}

	function getIdFromListBox($table,$field,$selectedItem)
	{
		$query="SELECT * FROM " . $table . " WHERE " . $field ."='".$selectedItem . "'" ;
		//echo $query;

		$results=r_db($query);

		$row=mysql_fetch_array($results);

		return $row[0];

	}

	function generateTextBox($label,$inputType, $name, $value)//Added by sumnesh on 29/07/03
	{
		echo  "<td>$label</td>";
		echo "<td><input type=$inputType name=$name value=$value></td>";
  	}
  	function  insertInLookUpTable($tblName,$field, $value)
  	{
  		$insertQuery = "INSERT INTO $tblName ($field) VALUES ('$value')";
  		r_db($insertQuery);
  		echo $insertQuery;
  	}
  	function  updateInLookUpTable($tblName,$field, $value, $tableId, $idValue)
  	{
  		$updateQuery = "UPDATE $tblName SET $field = '$value' WHERE $tableId=$idValue";
  		r_db($updateQuery);
  		echo $updateQuery;
  	}

function checkSessionITAdmin()
{
	if 	(empty($_SESSION['session_userType']))
	{
		echo "<CENTER><BR> Your Session has expired. Please Login again...";
		exit();
	}
	elseif 	($_SESSION['session_userType'] != 2)
	{
		echo "<CENTER> You don't have sufficient privileges. <BR> <BR> <BR> Only IT Administrator is allowed to do this task";
		exit();
	}
}


function row_color($i){
    $bg1 = "#E0EEFC"; // color one //light one
    $bg2 = "#FFFFFF"; // color two //dark one

    if ( $i%2 ) {
        return $bg1;
    } else {
        return $bg2;
    }
}

function userLogout()
{
	$_SESSION['session_username'] = NULL;
	unset($_SESSION['session_username']);
	// Unset all of the session variables.
	session_unset();
	// Finally, destroy the session.
	session_destroy();
}

function deleteRecordWithPK($table,$pk,$value)
{
$query = "DELETE FROM $table WHERE $pk= '$value'";
$sql = r_db($query);
}

function deleteRecordWithCompositePK($table, $pk1, $pk2, $value1, $value2)
{
$query = "DELETE FROM $table WHERE $pk1= '$value1' AND $pk2= '$value2'";
echo $query;
$sql = r_db($query);
echo "Record of " . $value1 . " has been sucessfully ";
echo "<BR>";
}

function createSessionSiteType($userType)
{
	// Register some session variables!
	session_register('session_siteType');
	$_SESSION['session_siteType'] = $userType;
	return $_SESSION['session_siteType'];
}

function getVisitColour($noOfVisits)
{
	if ($noOfVisits <=2)
	{
		$visitColour="#CCFFCC";
	}
	if ($noOfVisits ==3)
	{
		$visitColour="#FFCC66";
	}
	if ($noOfVisits >=4)
	{
		$visitColour="#FF6699";
	}

	return $visitColour;
}

function getmonthvisits($timegap,$siteid)
{
	$query="SELECT Count(er_visit.Visit_id) AS Total_visits FROM er_Client INNER JOIN er_visit ON er_Client.Client_ID=er_visit.Client_ID
			WHERE ((er_visit.visit_date <= now()) and er_visit.visit_date >= date_add(now(),interval -".$timegap." month)) AND ((er_visit.Site_Visited_ID)='".$siteid."')";
	//echo $query;

	$results=r_db($query);

	list($monthvisits)=mysql_fetch_array($results);

	return $monthvisits;

}

//Managers all errors
function error_handler($number, $message, $file, $line) {
	// Match the formatting, CSS, etc., for your site's style!
	echo '<p>The following error occurred, allegedly on line ' . $line . ' of file ' . $file . ':<br />' . $message . '</p>';
	//echo '<p>The existing variables are:<pre>' . print_r($GLOBALS, 1) . '</pre></p>';
}

//Generates a random string of $length
function random_string($length){
    $st=array(48,65,97);
    $en=array(57,90,122);
    $chr="";
    for($i=0;$i<$length;$i++){
    $rnd=rand(0,2);
        $chr.=chr(rand($st[$rnd],$en[$rnd]));
    }
    return $chr;
}

//saves search results or retrieves search results
function saveSearchResults() {
	if (isset($_POST)) {
		if (isset($_POST['txtNumber'])) {
			$txtNumber = $_POST['txtNumber'];
			setcookie("ERS_IDType", $txtNumber);
		}
		if (isset($_POST['txtNumber'])) {
			$cmbIdType = $_POST['cmbIdType'];
			setcookie("ERS_IDNumber", $cmbIdType);
		}
		if (isset($_POST['txtNumber'])) {
			$clientFirstName = $_POST['clientFirstName'];
			setcookie("ERS_ClientFirstName", $clientFirstName);
		}
		if (isset($_POST['txtNumber'])) {
			$clientLastName = $_POST['clientLastName'];
			setcookie("ERS_ClientLastName", $clientLastName);
		}
	}
}
function str_contains($haystack, $needle, $ignoreCase = false) 
{
	if ($ignoreCase) 
		{
			$haystack = strtolower($haystack);
			$needle  = strtolower($needle);
		}
	$needlePos = strpos($haystack, $needle);
	return ($needlePos === false ? false : ($needlePos+1));
}
function key_extract($key)
{
	if ($key == "sitename")
		return "Site Name";
	elseif ($key == "dateofvisit") 	
		return "Date of Visit";
	elseif ($key == "clientsurname") 	
		return "Surname of Client";
	elseif ($key == "clientfirstname") 	
 		return "First name of Client";
	elseif ($key == "clientidtypename") 	
		return "Client ID type-name";
	elseif ($key == "clientidnumber") 	
		return "Client ID Number";
	elseif ($key == "comment") 	
		return "Comment for Administrators";
	elseif ($key == "reportername") 	
		return "Reporting Persons Name";
	elseif ($key == "reportercontacttime") 	
		return "Suitable Contact Time";
	elseif ($key == "reporterphone") 	
		return "Contact Phone Number";
}

function getBeginEndYears () {
	//returns the begin and end years of the visit data
	$sql = "SELECT year(MIN( visit_date )) as start, year(MAX( visit_date))+2 as end FROM  `er_visit`";
	$result = r_db($sql);
	$row = mysql_fetch_array($result);
	return $row;
}

function getCurrentDate () {
	return date("l dS \of F Y");
}
function checkSSL() {
	global $sslEnabled;
	//Redirect to https if accessed over http (except when running locally)
	if ($_SERVER['SERVER_NAME'] != "localhost" && $sslEnabled == true)
	{
		$port = $_SERVER["SERVER_PORT"];
		$ssl_port = "443"; //Change 443 to whatever port you use for https (443 is the default and will work in most cases)
		if ($port != $ssl_port)
	{
	//$host = $_SERVER["HTTP_HOST"];
	$uri = $_SERVER["REQUEST_URI"];
	header("Location: https://weboo.biz$uri");
}
}
}

function testDB () {
	require_once 'MDB2.php';
	global $params;
	$dsn = $params[dsn];
	
	$mdb2 =& MDB2::factory($dsn);
	
	if (PEAR::isError($mdb2)) {
	    echo ($mdb2->getMessage().' - '.$mdb2->getUserinfo());
	    return false;
	}
	
	$query ='SELECT * FROM er_emergency_relief';
	
	// run the query and get a result handler
	$result = $mdb2->query($query);
	
	// check if the query was executed properly
	if (PEAR::isError($result)) {
	    echo ($result->getMessage().' - '.$result->getUserinfo());
	    return false;
	}
	
	// lets just get row:0 and free the result
	$array = $result->fetchRow();
	$result->free();
	return 	$array;
}
?>